package ee.siimkaspar.subjects.controller;

import java.math.BigInteger;
import java.security.MessageDigest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.opensymphony.xwork2.ActionContext;

import ee.siimkaspar.subjects.model.UserAccount;
import ee.siimkaspar.subjects.service.UserService;
import ee.siimkaspar.subjects.util.Const;

public class EntranceAction extends BaseAction {
	
	private String username;
	private String password;
	private String redirectUrl;
	private UserService uService;
	
	public EntranceAction(UserService uService) {
		this.uService = uService;
	}

	public String enter() {
		Logger.getLogger(getClass()).debug("enter");
		boolean isUserLoggedIn = (session.get(Const.SESSION_USER) instanceof UserAccount);
		boolean userExists = false;
		if (isUserLoggedIn) {
        	UserAccount user = (UserAccount) session.get(Const.SESSION_USER);
        	userExists = uService.findObject(UserAccount.class, user.getId()) != null;
        	if (userExists) {
                return LOGGED_IN;
            }
		}
		return SUCCESS;
	}
	
	public String login() {
		try {
			if (username != null && password != null) {
				MessageDigest md = MessageDigest.getInstance("MD5");
				md.update(password.getBytes());
				String hashedPsw = new BigInteger(1, md.digest()).toString(16);
				UserAccount user = uService.getAccountByUsernameAndPassword(username, hashedPsw);
				if (user != null) {
					session.put(Const.SESSION_USER, user);
					return SUCCESS;
				}
			}
		} catch (Exception e) {
			Logger.getLogger(getClass()).error("Error logging in. Message=" + e.getMessage());
		}
		addActionError("Wrong username or password!");
		return ERROR;
	}

	public String logout() {
		try {
			ActionContext ac = ActionContext.getContext();
			ac.getSession().clear();
			HttpSession httpSession = ((HttpServletRequest) ac
					.get(HTTP_REQUEST)).getSession(false);
			if (httpSession != null) {
				httpSession.invalidate();
			}
			addActionMessage("Logged out successfully!");
			if (redirectUrl != null) {
				return "redirect";
			} else {
				return SUCCESS;
			}
		} catch (Exception e) {
			System.out.println(e);
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public String error() {
		
		return SUCCESS;
	}
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRedirectUrl() {
		return redirectUrl;
	}

	public void setRedirectUrl(String redirectUrl) {
		this.redirectUrl = redirectUrl;
	}
	
}
